import { useEffect, useState } from "react"
import { useParams } from "react-router-dom"
import { message, Button, Spin, Space, Tag } from 'antd'

import FormDesigner from "../../components/FormDesigner"
import DetailHeader from "../../components/DetailHeader"
import CommonModalForm from "../../components/common/CommonModalForm"

import { queryDefinition, saveDefinition } from "../../apis/formDefinition"
import { formatFormItems, reformatFormItems } from '../../utils/formItems'
import ModelerSaveModal from "../../components/ModelerSaveModal"


// 转换请求数据格式
const formatFormDefinition = (responseData) => {
  const { id, name, key, version, lastUpdated, lastUpdatedBy, description, formDefinition } = responseData
  return {
    id, name, key, version, lastUpdated, lastUpdatedBy, description,
    formItems: formDefinition.fields ? formatFormItems(formDefinition.fields) : []
  }
}

// 转换提交数据格式
const reformatFormDefinition = (formDefinition, value, modelValues) => {
  const {
    id, version, lastUpdated, lastUpdatedBy,
  } = formDefinition

  const {
    formItems
  } = value

  const {
    name, key, description, comment, newversion
  } = modelValues

  const submitValues = {
    reusable: false,
    newVersion: !!newversion,
    comment: comment || '',
    formImageBase64: "formImageBase64",
    formRepresentation: {
      id, version, lastUpdated, lastUpdatedBy,
      name, key, description,
      formDefinition: {
        name,
        key,
        outcomes: [],
        fields: reformatFormItems(formItems)
      }
    }
  }

  return submitValues
}

const ModelerFormDesign = () => {

  const { id: modelId } = useParams()
  const [loading, setLoading] = useState(false)

  const [formDefinition, setFormDefinition] = useState({})
  const [value, setValue] = useState({})

  // 请求表单设计数据
  const doQueryFormDefinition = async () => {
    setLoading(true)
    try {
      const data = await queryDefinition(modelId)
      const formDefinitionData = formatFormDefinition(data)

      setFormDefinition(formDefinitionData)
      setValue(JSON.parse(JSON.stringify(formDefinitionData)))

    } catch (error) {
      message.error(error.message || 'formModel查询失败')
    }
    setLoading(false)
  }

  // 提交表单设计数据
  const handleSave = async (modelValues, callbacks = {}) => {
    const submitValues = reformatFormDefinition(formDefinition, value, modelValues)
    try {
      await saveDefinition(modelId, submitValues)
      message.success('保存成功')
      callbacks.hideModal && callbacks.hideModal()
      callbacks.clearSending && callbacks.clearSending()
      doQueryFormDefinition()
    } catch (error) {
      callbacks.clearSending && callbacks.clearSending()
      message.error(error.message || '保存失败！')
    }
  }

  const [previewVisible, setPreviewVisible] = useState(false)
  const togglePreview = () => {
    setPreviewVisible(!previewVisible)
  }

  useEffect(() => {
    if (modelId) {
      doQueryFormDefinition()
    }
  }, [modelId])

  const renderHeadTitle = () => {
    return <>
      <b style={{ fontSize: 18 }}>{formDefinition.name}</b>
      <Tag color="blue">v{formDefinition.version}</Tag>
    </>
  }

  const renderHeadBtns = () => {
    return <Space>
      <Button onClick={togglePreview}>预览</Button>
      <ModelerSaveModal
        modelMetaData={{
          name: value.name,
          key: value.key,
          description: value.description
        }}
        onSubmit={handleSave}
      ></ModelerSaveModal>
    </Space>
  }

  return <Spin spinning={loading} wrapperClassName="page-wrap">
    <CommonModalForm
      title="表单预览"
      visible={previewVisible}
      formItems={value.formItems}
      onCancel={togglePreview}
    ></CommonModalForm>
    <DetailHeader
      title={renderHeadTitle()}
      extra={renderHeadBtns()}
    ></DetailHeader>
    <div style={{
      flex: 1,
      height: '100%',
      overflow: 'auto',
      margin: '10px 0'
    }}>
      <FormDesigner
        value={value}
        onChange={setValue}
      ></FormDesigner>
    </div>
  </Spin>
}

export default ModelerFormDesign